package com.tanhua.server.service;

import cn.hutool.core.collection.CollUtil;
import com.github.tobato.fastdfs.domain.conn.FdfsWebServer;
import com.github.tobato.fastdfs.domain.fdfs.StorePath;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import com.tanhua.autoconfig.templates.OssTemplate;
import com.tanhua.commons.utils.Constants;
import com.tanhua.dubbo.api.UserInfoApi;
import com.tanhua.dubbo.api.VideoApi;
import com.tanhua.model.db.UserInfo;
import com.tanhua.model.mongo.Video;
import com.tanhua.model.vo.PageResult;
import com.tanhua.model.vo.VideoVo;
import com.tanhua.server.interceptor.UserHolder;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Service
public class SmallVideosService {

    @Autowired
    private OssTemplate ossTemplate;

    @Autowired
    private FastFileStorageClient client;

    @Autowired
    private FdfsWebServer webServer;

    @DubboReference
    private VideoApi videoApi;

    @DubboReference
    private UserInfoApi userInfoApi;

    @Autowired
    private StringRedisTemplate redisTemplate;

    /**
     * 发布视频
     *  1、文件上传到服务器
     *  2、保存Video到数据库中
     */
    public void saveVideo(MultipartFile videoThumbnail, MultipartFile videoFile)
            throws IOException {
        //1、封面图片上传到阿里云oss
        String picUrl = ossTemplate.upload(videoThumbnail.getInputStream(),
                videoThumbnail.getOriginalFilename());
        //2、视频上传到fastdfs
        String filename = videoFile.getOriginalFilename();//xxxxxx.mp4
        int index = filename.lastIndexOf(".");
        filename = filename.substring(index+1);
        StorePath storePath = client.uploadFile(videoFile.getInputStream(),
                videoFile.getSize(),
                filename,
                null);//文件输入流，文件大小，后缀名，元数据
        //拼接url
        String videoUrl = webServer.getWebServerUrl() + storePath.getFullPath();
        //3、构造Video对象
        Video video = new Video();
        video.setUserId(UserHolder.getUserId());
        video.setCreated(System.currentTimeMillis());
        video.setText("我就是我，是颜色不一样的烟火");
        video.setPicUrl(picUrl);
        video.setVideoUrl(videoUrl);
        //4、调用API保存
        videoApi.save(video);
    }


    /**
     * 查询视频列表（有推荐的查询推荐，没有推荐查询数据库中的所有）
     */
    public PageResult findVideos(Integer page, Integer pagesize) {
        //1、从redis中查询推荐的视频
        String key = Constants.VIDEOS_RECOMMEND + UserHolder.getUserId();
        String value = redisTemplate.opsForValue().get(key);
        //2、判断是否存在  List<Video>
        List<Video> list = new ArrayList<>();
        if(!StringUtils.isEmpty(value)) {
            //2.1 如果存在，根据视频id集合查询视频
            String[] vids = value.split(",");
            list = videoApi.findByIds(vids,page,pagesize);
        }else {
            //2.2 如果不存在，查询所有视频
            list = videoApi.findAll(page,pagesize);
        }
        if(CollUtil.isEmpty(list)) {
            return new PageResult();
        }
        //一次性查询获取所有的视频发布人信息
        List<Long> ids = CollUtil.getFieldValues(list, "userId", Long.class);
        Map<Long, UserInfo> map = userInfoApi.findByIds(ids);
        //3、将一个Video转化一个VideoVo
        List<VideoVo> vos = new ArrayList<>();
        for (Video video : list) {
            Long userId = video.getUserId();
            UserInfo userInfo = map.get(userId);//视频发布人的信息
            VideoVo vo = VideoVo.init(userInfo, video);
            vos.add(vo);
        }
        //4、返回
        return new PageResult(page,pagesize,0l,vos);
    }

    @Autowired
    private MqMessageService mqMessageService;

    //视频点赞
    public void like(String videoId) {
        Long userId = UserHolder.getUserId();
        //完成点赞业务逻辑
        //发送日志消息
        mqMessageService.sendLogMessage(userId,"0302","log.video",videoId);
    }
}
